#!/bin/bash

# 检查是否为root用户
if [[ "$(id -u)" != "0" ]]; then
    echo "请使用root用户执行"
    exit 1
fi

# 安装必要的包
echo "安装ftp和vsftpd..."
yum -y install vsftpd ftp || {
    echo "安装失败"
    exit 1
}

TEST_USER="test"
DB_FILE="/etc/vsftpd/virtusers"
DB_TYPE_INFO=$(ldd /usr/lib64/security/pam_userdb.so)
# 备份vsftpd.conf文件
\cp /etc/vsftpd/vsftpd.conf /etc/vsftpd/vsftpd.conf.bak

# 配置vsftpd,直接覆盖
cat > /etc/vsftpd/vsftpd.conf << EOF
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
dirmessage_enable=YES
xferlog_enable=YES
connect_from_port_20=YES
xferlog_std_format=YES
chroot_local_user=YES
allow_writeable_chroot=YES
chroot_list_file=/etc/vsftpd/chroot_list
listen=YES
listen_ipv6=NO
pam_service_name=vsftpd
userlist_enable=NO

# 虚拟用户配置
guest_enable=YES
guest_username=ftp
virtual_use_local_privs=YES
allow_writeable_chroot=YES
user_config_dir=/etc/vsftpd/user_conf
EOF

# 判断使用db_load还是gdbmtool
if echo "${DB_TYPE_INFO}" | grep -q "libdb"; then
    cat > ${DB_FILE}.txt << EOF
${TEST_USER}
${PASSWORD}
EOF

    db_load -T -t hash -f ${DB_FILE}.txt ${DB_FILE}.db
elif echo "${DB_TYPE_INFO}" | grep -q "libgdbm"; then
    gdbmtool ${DB_FILE}.pag <<EOF
store ${TEST_USER}
${PASSWORD}
quit
EOF
else
    echo "[ERROR] 无法确定数据库工具，请检查 pam_userdb.so 的依赖"
    exit 1
fi

# 创建用户列表
cat > /etc/vsftpd/user_list << EOF
${TEST_USER}
EOF

# 创建用户配置目录和文件
mkdir -p /etc/vsftpd/user_conf
echo "local_root=/data/ftp/${TEST_USER}" > /etc/vsftpd/user_conf/${TEST_USER}

# 配置PAM认证
cat > /etc/pam.d/vsftpd << EOF
#%PAM-1.0
session    optional     pam_keyinit.so    force revoke
auth    sufficient      /lib64/security/pam_userdb.so    db=${DB_FILE}
account sufficient      /lib64/security/pam_userdb.so    db=${DB_FILE}
EOF

# 重启服务
systemctl restart vsftpd
systemctl enable vsftpd
systemctl status vsftpd

if [[ $? -eq 0 ]]
then
    echo "vstpd安装成功"
    # 输出配置信息
    echo "测试用户: ${TEST_USER}"
    echo "测试密码: ${PASSWORD}"
else
    echo "vsftpd安装失败"
fi